<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const loading = ref(false)
const form = ref({
    nickname: '',
    email: '',
    avatar: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const rules = {
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    newPassword: [
        { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        {
            validator: (rule, value, callback) => {
                if (form.value.newPassword && value !== form.value.newPassword) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

const formRef = ref(null)

const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
        return false
    }
    return true
}

const handleAvatarSuccess = (res) => {
    if (res.code === 200) {
        form.value.avatar = res.data
    } else {
        ElMessage.error('上传失败')
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                
                // 如果修改了密码，先更新密码
                if (form.value.oldPassword && form.value.newPassword) {
                    await updatePassword({
                        oldPassword: form.value.oldPassword,
                        newPassword: form.value.newPassword
                    })
                }
                
                // 更新用户信息
                await updateUserInfo({
                    nickname: form.value.nickname,
                    email: form.value.email,
                    avatar: form.value.avatar
                })
                
                ElMessage.success('保存成功')
                await userStore.fetchCurrentUser()
                
                // 清空密码字段
                form.value.oldPassword = ''
                form.value.newPassword = ''
                form.value.confirmPassword = ''
            } catch (error) {
                ElMessage.error(error.response?.data?.message || '保存失败')
            } finally {
                loading.value = false
            }
        }
    })
}

onMounted(() => {
    // 初始化表单数据
    if (userStore.currentUser) {
        form.value.nickname = userStore.currentUser.nickname
        form.value.email = userStore.currentUser.email
        form.value.avatar = userStore.currentUser.avatar
    }
})
</script>

<template>
    <div class="settings">
        <h2>个人设置</h2>
        <el-form 
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
        >
            <el-form-item label="头像">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                >
                    <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" />
            </el-form-item>
            
            <el-divider>修改密码（选填）</el-divider>
            
            <el-form-item label="原密码" prop="oldPassword">
                <el-input 
                    v-model="form.oldPassword"
                    type="password"
                    show-password
                />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
                <el-input 
                    v-model="form.newPassword"
                    type="password"
                    show-password
                />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                    v-model="form.confirmPassword"
                    type="password"
                    show-password
                />
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleSubmit">
                    保存修改
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped lang="scss">
.settings {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    h2 {
        margin-bottom: 30px;
        text-align: center;
        color: #333;
    }
}

.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}
</style> 